<template>
  <div class="content">
    <i-tabs :current="activeType" color="#ef250b" @change="handleTabChange">
      <i-tab v-for="(item,index) in transType" :key="index" :title="item.name"></i-tab>
    </i-tabs>
    <scroll-view class="scroll-wrap" scroll-y @scrolltolower="handleLoadMore">
      <div class="wu"></div>
      <div class="list" v-for="(item,index) in orderList" :key="index">
        <div class="margin" @click="findStockGoodsInfoLinkClick(item)">
          <img :src="item.goodsImage" mode="scaleToFill" />
          <div class="right">
            <p class="ellipsis-2">{{item.goodsName}}</p>
            <div>
              <span>￥{{item.goodsAmount}}</span>
              <p>×{{item.goodsNum}}</p>
            </div>
            <p class="allMoney">
              总价：
              <span>￥{{item.realAmount}}</span>
            </p>
          </div>
        </div>
        <div class="btnBox">
          <button
            v-if="item.state === '1' || item.state === '8'"
            @click="stockreFund(item)"
          >申请退货</button>
          <!-- <button v-if="item.state === '3'" @click="stockreFund(item)">申请退货</button> 李阳说的=3 -->
          <!-- <button @click="stockreFund(item)">申请退货</button> -->
          <button
            v-if="(item.state === '1' || item.state === '4' || item.state === '8' ) && item.shippingMode === '0'"
            @click="findLogisticsClick(item)"
          >查看物流</button>
          <button
            class="take"
            v-if="item.state === '1'|| item.state === '8' && item.shippingMode === '0'"
            @click="orderTakeClick(item)"
          >确认收货</button>

          <button v-if="item.state === '0'" @click="cancelOrderClick(item)">取消订单</button>
          <button
            class="take"
            v-if="item.state === '0'"
            @click="payClcik(item)"
          >立即支付</button>
          <button v-if="item.state === '2'">已取消</button>
          <button v-if="item.state === '3'">已收货</button>
          <button v-if="item.state === '4'" @click="refundClick(item)">退款中</button>
          <button v-if="item.state === '5'">已退款</button>
          <!-- 被拒绝了可以不停申请 -->
          <!-- <button v-if="item.state === '8'">拒绝退款</button> -->
        </div>
      </div>
      <p v-if="alreadyLastPage" class="end-tip">没有更多了</p>
    </scroll-view>
  </div>
</template>

<script>
import {
  FIND_STOCK_ORDER_PAGE_API,
  CONFIRM_ORDER_STATE,
  ADD_STOCK_GOODS_LIST,
  FIND_REFUND_PAGE_API,
  FIND_REFUND_RATIO,
  AGREE_REFUND,
  CANCEL_ORDER_API,
  FIND_USER_OPEN_ID,
  CREATE_STOCK_SHOPPING_FEEPAY_ORDER,
  CREATE_STOCKRE_FUND,
  CONFIRM_ORDER
} from '@/api'
// import { getCurrentPageParams } from '@/utils'
import { Base64 } from 'js-base64'

export default {
  components: {},
  props: {},
  data () {
    return {
      currentPage: 1,
      alreadyLastPage: false,
      list: [],
      activeType: '0',
      state: '',
      transType: [
        { key: '0', name: '全部', state: '' },
        { key: '1', name: '待付款', state: '0' },
        { key: '2', name: '待收货', state: '1' },
        { key: '3', name: '已收货', state: '3,7' },
        { key: '4', name: '退货', state: '4,5,8' }
      ],
      orderState: {
        '0': '待付款',
        '1': '待收货',
        '2': '已取消',
        '3': '已收货',
        '4': '退款中',
        '5': '已退款',
        // '6': '用户删除订单',
        '7': '已评价',
        '8': '拒绝退款'
      },
      openId: ''
    }
  },
  computed: {
    account () {
      return this.$store.state.account
      // return this.$cookie.get('account')
    },
    orderList () {
      return this.list.map(_ => ({
        ..._,
        realAmount: _.goodsAmount * _.goodsNum
      }))
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.activeType = '0'
    this.init()
    this.getwxCode()
    this._findShopList()
  },
  methods: {
    handleTabChange (e) {
      this.activeType = e.target.key
      this.init()
      this.transType.forEach(_ => {
        if (this.activeType === _.key) {
          this.state = _.state
          this._findShopList()
        }
      })
    },
    handleLoadMore () {
      if (!this.alreadyLastPage) {
        this._findShopList()
      }
    },
    findStockGoodsInfoLinkClick (item) {
      this.$router.push(
        `/pages/data-analyze/stock/my/order-info/main?orderNo=${item.orderNo}`
      )
    },
    orderTakeClick (item) {
      const vm = this
      vm
        .$dialog('是否确定收货', '', '#ef250b')
        .then(() => {
          if (!item.shippingFee) {
            vm.confirmOrderState(item)
          } else {
            vm.confirmOrderStateYesMoney(item)
          }
          // 支付的东西
          // vm.$router.push(
          //   `/pages/open-shop/open-shop-pay/main?amount=${
          //     vm.formData.amount
          //   }&openShopOrderNo=${vm.formData.openShopOrderNo}&customerId=${
          //     vm.formData.customerId
          //   }&shopIdentity=${vm.formData.shopIdentity}`
          // )
        })
        .catch(() => {})
    },
    findLogisticsClick (item) {
      this.$router.push(
        `/pages/data-analyze/stock/my/logistics/main?orderNo=${item.orderNo}`
      )
    },
    cancelOrderClick (item) {
      const vm = this
      vm.$dialog('是否确定取消订单', '', '#ef250b').then(() => {
        vm.cancelOrderApi(item)
      })
    },
    refundClick (item) {
      let str = JSON.stringify(item)
      this.$router.push(
        `/pages/data-analyze/stock/my/apply-money-cancel/main?item=${str}`
      )

      // this._findAgreeRefund(item)
    },
    stockreFund (item) {
      const vm = this
      vm.$dialog('是否确认申请退货', '', '#ef250b').then(() => {
        // vm._createStockReFund(item)
        let str = JSON.stringify(item)
        if (item.state === '8') {
          vm.$router.push(
            `/pages/data-analyze/stock/my/apply-again-info-show/main?item=${str}`
          )
        } else {
          vm.$router.push(
            `/pages/data-analyze/stock/my/apply-money/main?item=${str}`
          )
        }
      })
    },
    payClcik (item) {
      const vm = this
      vm.$dialog('是否确定支付订单', '', '#ef250b').then(() => {
        vm.payOrder(item)
      })
    },
    getwxCode () {
      const vm = this
      wx.login({
        timeout: 6000,
        success: function (res) {
          vm._getWxCode(res.code)
        },
        fail: function (err) {
          console.error(err)
        }
      })
    },
    init () {
      const vm = this
      vm.currentPage = 1
      vm.alreadyLastPage = false
      vm.list = []
    },

    /** api **/
    confirmOrderState (item) {
      const vm = this
      // CONFIRM_ORDER_STATE(item.orderNo, item.shopId) // 改了 取消了shopId
      CONFIRM_ORDER_STATE(item.orderNo)
        .then(r => {
          if (r.data.code === '0') {
            vm.addStockGoodsList(item)
            vm.$toast('收货成功')
            vm.init()
            vm._findShopList()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 无运费的时候
    confirmOrderStateYesMoney (item) {
      const vm = this
      // CONFIRM_ORDER_STATE(item.orderNo, item.shopId) // 改了 取消了shopId
      CONFIRM_ORDER(item.orderNo)
        .then(r => {
          if (r.data.code === '0') {
            vm.addStockGoodsList(item)
            vm.$toast('收货成功')
            vm.init()
            vm._findShopList()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 有运费的时候
    cancelOrderApi (item) {
      const vm = this
      CANCEL_ORDER_API(item.orderNo)
        .then(r => {
          if (r.data.code === '0') {
            vm.$toast('取消订单成功')
            vm.init()
            vm._findShopList()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    _getWxCode (code) {
      const vm = this
      let appId = vm.$store.state.appId
      let appSecret = Base64.decode(vm.$store.state.appSecret)
      FIND_USER_OPEN_ID(appId, appSecret, code)
        .then(r => {
          if (r.data.code === '0') {
            vm.openId = r.data.data
          } else {
            this.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    payOrder (item) {
      const vm = this
      let params = {
        appId: 23,
        openId: vm.openId,
        orderNo: item.orderNo,
        payMerId: vm.$store.state.payMerId,
        payMethodEnum: 'MINI',
        paySourceEnum: 'H5',
        relateMan: vm.account.shopId,
        shopAppId: 23
      }
      CREATE_STOCK_SHOPPING_FEEPAY_ORDER(params)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.data) {
              let payInfo = Base64.decode(r.data.data.data)
              vm._callWechatPay(JSON.parse(payInfo))
            }
          } else if (r.data.message === '未找到云账户信息') {
            vm
              .$alert(
                '您暂未开通云账户，请到爱卡卡开店宝pc端管理系统登录开通。详情请咨询400-888-5115'
              )
              .then(r => {
                vm.$router.go(-1)
              })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {})
    },
    _callWechatPay (payInfo) {
      const vm = this
      wx.requestPayment({
        ...payInfo,
        success: function (res) {
          vm.$alert('支付成功', '').then(() => {
            vm._findShopList()
          })
        },
        fail: function (err) {
          if (err.errMsg === 'requestPayment:fail cancel') {
          } else {
            vm.$toast('支付失败')
          }
        }
      })
    },
    addStockGoodsList (item) {
      const vm = this
      ADD_STOCK_GOODS_LIST(item.orderNo)
        .then(r => {
          if (r.data.code === '0') {
            vm.$toast('将进货商品添加至分销商商品列表成功')
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    _findAgreeRefund (item, num = '0') {
      const vm = this
      let params = {
        orderNo: item.orderNo,
        providerId: vm.account.providerId,
        shopId: vm.account.shopId
      }
      FIND_REFUND_PAGE_API(params, 1, 999)
        .then(r => {
          if (r.data.code === '0') {
            let data = r.data.data.list[0]
            if (num === '0') {
              vm._serviceRefund(data)
            } else {
              // 这个页面没有拒绝退款
              // vm._rejectRefund(data)
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 查询单条退款详情
    _createStockReFund (item) {
      const vm = this
      let params = {
        customerId: vm.account.providerId || vm.account.shopId,
        orderNo: item.orderNo,
        providerId: vm.account.providerId,
        reason: '',
        refundId: '',
        shopId: vm.account.shopId,
        state: item.state,
        tradeNo: '',
        amount: 0
      }
      CREATE_STOCKRE_FUND(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.$toast('申请退货成功')
            vm.init()
            vm._findShopList()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    _serviceRefund (data) {
      const vm = this
      FIND_REFUND_RATIO(data.refundId, data.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.refundNum = r.data.data
            // this.$dialog(
            //   '手续费为' + this.refundNum + '元,是否确认退款',
            //   ''
            // )
            vm.$dialog('是否继续退款操作', '', '#ef250b').then(() => {
              vm._confirmRefund(data)
            })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 查询手续费
    _confirmRefund (data) {
      const vm = this
      AGREE_REFUND(data.refundId, data.shopId, vm.refundNum)
        .then(r => {
          if (r.data.data === '0') {
            vm.$alert('退款成功', '').then(() => {
              vm.init()
              vm._findShopList()
            })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 确认退款
    _findShopList () {
      const vm = this
      let params = {
        state: vm.state,
        // customerId: vm.account.customerId || vm.account.shopId, // 进货圈都没有customerId
        customerId: vm.account.shopId,
        isStock: '1'
      }
      FIND_STOCK_ORDER_PAGE_API(params, vm.currentPage, 10)
        .then(r => {
          if (r.data.code === '0') {
            let { isFirstPage, isLastPage, list } = r.data.data
            vm.printList(list, isFirstPage, isLastPage)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 商品列表
    printList (list, isFirst, isLast) {
      const vm = this
      if (isFirst) {
        vm.list = list
        if (isLast || !list.length) {
          vm.alreadyLastPage = true
        } else {
          vm.alreadyLastPage = false
          vm.currentPage += 1
        }
      } else if (isLast) {
        vm.alreadyLastPage = true
        vm.list.push(...list)
      } else {
        vm.list.push(...list)
        vm.alreadyLastPage = false
        vm.currentPage += 1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';
.content {
  background: #f6f8f9;
  > .scroll-wrap {
    height: calc(100% - 42px);
    .wu {
      height: 15px;
    }
    .list {
      width: 100%;
      background: #fff;
      margin-bottom: 15px;
      .margin {
        width: 90%;
        margin: auto;
        display: flex;
        align-items: center;
        padding: 15px 0;
        img {
          width: 75px;
          height: 75px;
          border-radius: 6px;
        }
        .right {
          width: calc(100% - 75px - 15px);
          height: 75px;
          margin-left: 15px;
          font-size: 14px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          p {
            color: #000;
          }
          div {
            display: flex;
            align-items: center;
            justify-content: space-between;
            p {
              font-size: 12px;
              color: #727272;
            }
          }
          .allMoney {
            span {
              color: #f24d38;
            }
          }
        }
      }
      .btnBox {
        width: 100%;
        border-top: 1px solid #f7f8fa;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        button {
          margin: 20px 5px;
          border-radius: 25px;
          background: #fff;
          border: 1px solid #6a6a6a;
          color: #6a6a6a;
          font-size: 13px;
          line-height: 30px;
        }
        .take {
          border: 1px solid #ef250b;
          color: #ef250b;
        }
      }
    }
    .end-tip {
      margin: 0;
      padding: 15px;
      text-align: center;
      color: $gray;
      font-size: 15px;
    }
  }
}
</style>
